﻿using SqlSugar;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using XMFramework.Models;
using XMFramework.MysqlService;

namespace XMFramework.Forms.Pages.Orders
{
    public partial class FProductionOrder : UIPage
    {
        private SqlSugarScope db = SqlSugarHelper.Db;
        List<ProductionOrderModel> orderlist = new List<ProductionOrderModel>();
        DataTable order_dt = new DataTable();//订单表
        DataTable recipe_dt = new DataTable();//工艺表
        DataTable device_dt = new DataTable();//模具表
        public FProductionOrder()
        {
            InitializeComponent();
            //***********内部表格,必须代码添加（订单编号）**************
            //**************过滤*************
            uiComboDataGridView1.ItemSize = new Size(800, 300);
            uiComboDataGridView1.ShowFilter = true;
            uiComboDataGridView1.FilterColumnName = "materialCode"; //不设置则全部列过滤

            //uiComboDataGridView1.DataGridView.Init();
            uiComboDataGridView1.DataGridView.AddColumn("id", "id");
            uiComboDataGridView1.DataGridView.AddColumn("contractCode", "contractCode");
            uiComboDataGridView1.DataGridView.AddColumn("materialCode", "materialCode");
            uiComboDataGridView1.DataGridView.AddColumn("productName", "productName");
            uiComboDataGridView1.DataGridView.AddColumn("remainder", "remainder");
            uiComboDataGridView1.DataGridView.AddColumn("orderNumber", "orderNumber");
            uiComboDataGridView1.DataGridView.AddColumn("deliveryDate", "deliveryDate");
            uiComboDataGridView1.DataGridView.Columns["id"].HeaderText = "订单编号";
            uiComboDataGridView1.DataGridView.Columns["contractCode"].HeaderText = "合同号";
            uiComboDataGridView1.DataGridView.Columns["materialCode"].HeaderText = "物料编码";
            uiComboDataGridView1.DataGridView.Columns["productName"].HeaderText = "产品名称";
            uiComboDataGridView1.DataGridView.Columns["remainder"].HeaderText = "剩余数量";
            uiComboDataGridView1.DataGridView.Columns["orderNumber"].HeaderText = "总数量";
            uiComboDataGridView1.DataGridView.Columns["deliveryDate"].HeaderText = "交期";

            //uiComboDataGridView1.DataGridView.Columns["id"].Visible = false;
            uiComboDataGridView1.DataGridView.Columns["id"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            uiComboDataGridView1.DataGridView.Columns["contractCode"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            uiComboDataGridView1.DataGridView.Columns["materialCode"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            uiComboDataGridView1.DataGridView.Columns["productName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            uiComboDataGridView1.DataGridView.Columns["remainder"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            uiComboDataGridView1.DataGridView.Columns["orderNumber"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            uiComboDataGridView1.DataGridView.Columns["deliveryDate"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            //设置表格
            uiComboDataGridView1.DataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            uiComboDataGridView1.DataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
            uiComboDataGridView1.DataGridView.ReadOnly = true;
            uiComboDataGridView1.DataGridView.AllowUserToAddRows = false;

            //***********内部表格,必须代码添加（工艺编号）**************
            //**************过滤*************
            uiComboDataGridView2.ItemSize = new Size(600, 300);
            uiComboDataGridView2.ShowFilter = true;
            uiComboDataGridView2.FilterColumnName = "processCode"; //不设置则全部列过滤

            //uiComboDataGridView2.DataGridView.Init();
            uiComboDataGridView2.DataGridView.AddColumn("id", "id");
            uiComboDataGridView2.DataGridView.AddColumn("processCode", "processCode");
            uiComboDataGridView2.DataGridView.AddColumn("epsDensity", "epsDensity");
            uiComboDataGridView2.DataGridView.AddColumn("mouldCode", "mouldCode");
            uiComboDataGridView2.DataGridView.AddColumn("singleNumber", "singleNumber");
            uiComboDataGridView2.DataGridView.AddColumn("notes", "notes");
            uiComboDataGridView2.DataGridView.Columns["processCode"].HeaderText = "工艺编号";
            uiComboDataGridView2.DataGridView.Columns["epsDensity"].HeaderText = "原料密度";
            uiComboDataGridView2.DataGridView.Columns["mouldCode"].HeaderText = "模具编号";
            uiComboDataGridView2.DataGridView.Columns["singleNumber"].HeaderText = "模具产品数";
            uiComboDataGridView2.DataGridView.Columns["notes"].HeaderText = "备注";

            uiComboDataGridView2.DataGridView.Columns["id"].Visible = false;
            uiComboDataGridView2.DataGridView.Columns["id"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            uiComboDataGridView2.DataGridView.Columns["processCode"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            uiComboDataGridView2.DataGridView.Columns["epsDensity"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            uiComboDataGridView2.DataGridView.Columns["mouldCode"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            uiComboDataGridView2.DataGridView.Columns["singleNumber"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            uiComboDataGridView2.DataGridView.Columns["notes"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            //设置表格
            uiComboDataGridView2.DataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            uiComboDataGridView2.DataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
            uiComboDataGridView2.DataGridView.ReadOnly = true;
            uiComboDataGridView2.DataGridView.AllowUserToAddRows = false;

            //***********内部表格,必须代码添加（设备编号）**************
            //**************过滤*************
            uiComboDataGridView3.ItemSize = new Size(600, 300);
            uiComboDataGridView3.ShowFilter = true;
            uiComboDataGridView3.FilterColumnName = "mouldCode"; //不设置则全部列过滤

            //uiComboDataGridView3.DataGridView.Init();
            uiComboDataGridView3.DataGridView.AddColumn("id", "id");
            uiComboDataGridView3.DataGridView.AddColumn("deviceType", "deviceType");
            uiComboDataGridView3.DataGridView.AddColumn("deviceCode", "deviceCode");
            uiComboDataGridView3.DataGridView.AddColumn("pn", "pn");
            uiComboDataGridView3.DataGridView.AddColumn("notes", "notes");
            uiComboDataGridView3.DataGridView.Columns["id"].HeaderText = "系统编号";
            uiComboDataGridView3.DataGridView.Columns["deviceType"].HeaderText = "设备类型";
            uiComboDataGridView3.DataGridView.Columns["deviceCode"].HeaderText = "设备号";
            uiComboDataGridView3.DataGridView.Columns["notes"].HeaderText = "备注";
            uiComboDataGridView3.DataGridView.Columns["pn"].HeaderText = "网关PN";
            uiComboDataGridView3.DataGridView.Columns["id"].Visible = false;
            uiComboDataGridView3.DataGridView.Columns["id"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            uiComboDataGridView3.DataGridView.Columns["deviceType"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            uiComboDataGridView3.DataGridView.Columns["deviceCode"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            uiComboDataGridView3.DataGridView.Columns["pn"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            uiComboDataGridView3.DataGridView.Columns["notes"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            //设置表格
            uiComboDataGridView3.DataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            uiComboDataGridView3.DataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
            uiComboDataGridView3.DataGridView.ReadOnly = true;
            uiComboDataGridView3.DataGridView.AllowUserToAddRows = false;
        }

        private void FProductionOrders_Initialize(object sender, EventArgs e)
        {
            //每次打开页面初始化
            uiDatePicker2.Text = DateTime.Now.ToString("yyyy-MM-dd");
            //订单查询
            try
            {
                db.BeginTran();

                order_dt = db.Queryable<OrderModel>().Select(it => new { it.id, it.contractCode, it.materialCode, it.productName, it.remainder, it.orderNumber, it.deliveryDate }).OrderBy(it => it.id, OrderByType.Desc).ToDataTable();

                db.CommitTran();
            }
            catch (Exception ex)
            {
                db.RollbackTran();//数据回滚
                UIMessageTip.ShowError("插入失败 - 数据回滚!\n" + ex);
            }
            //工艺查询
            try
            {
                db.BeginTran();

                recipe_dt = db.Queryable<RecipeModel>().Select(it => new { it.id, it.processCode, it.epsDensity, it.mouldCode, it.singleNumber, it.notes }).OrderBy(it => it.id, OrderByType.Desc).ToDataTable();

                db.CommitTran();
            }
            catch (Exception ex)
            {
                db.RollbackTran();//数据回滚
                UIMessageTip.ShowError("插入失败 - 数据回滚!\n" + ex);
            }
            //设备查询
            try
            {
                db.BeginTran();

                device_dt = db.Queryable<DeviceModel>()
                    .Select(it => new { it.id, it.deviceType, it.deviceCode, it.pn, it.notes })
                    .OrderBy(it => it.id, OrderByType.Desc).ToDataTable();

                db.CommitTran();
            }
            catch (Exception ex)
            {
                db.RollbackTran();//数据回滚
                UIMessageTip.ShowError("插入失败 - 数据回滚!\n" + ex);
            }

            uiComboDataGridView1.DataGridView.DataSource = order_dt;//订单
            uiComboDataGridView2.DataGridView.DataSource = recipe_dt;//工艺
            uiComboDataGridView3.DataGridView.DataSource = device_dt;//设备

            if (!backgroundWorker1.IsBusy)
                backgroundWorker1.RunWorkerAsync();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                db.BeginTran();
                orderlist = db.Queryable<ProductionOrderModel>().Where(it => it.state == "新增").OrderBy(it => it.id, OrderByType.Desc).ToList();
                db.CommitTran();
            }
            catch (Exception ex)
            {
                db.RollbackTran();//数据回滚
                UIMessageTip.ShowError("插入失败 - 数据回滚!\n" + ex);
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            uiDataGridView1.DataSource = orderlist;
            uiSymbolButton2.Enabled = false;
            uiSymbolButton5.Enabled = false;
            uiSymbolButton6.Enabled = false;
        }

        private void uiDataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                uiTextBox8.Text = uiDataGridView1.Rows[e.RowIndex].Cells["id"].Value.ToString();//生产编号
                uiComboDataGridView1.Text = uiDataGridView1.Rows[e.RowIndex].Cells["orderCode"].Value.ToString();//订单编号
                uiTextBox10.Text = uiDataGridView1.Rows[e.RowIndex].Cells["contractCode"].Value.ToString();//合同号
                uiTextBox12.Text = uiDataGridView1.Rows[e.RowIndex].Cells["materialCode"].Value.ToString();//物料编码
                uiComboDataGridView2.Text = uiDataGridView1.Rows[e.RowIndex].Cells["recipeCode"].Value.ToString();//工艺编号
                uiComboDataGridView3.Text = uiDataGridView1.Rows[e.RowIndex].Cells["deviceCode"].Value.ToString();//设备编号
                uiTextBox2.Text = uiDataGridView1.Rows[e.RowIndex].Cells["moldCode"].Value.ToString();//模具编号
                uiTextBox9.Text = uiDataGridView1.Rows[e.RowIndex].Cells["singleNumber"].Value.ToString();//模具产品数
                uiTextBox1.Text = uiDataGridView1.Rows[e.RowIndex].Cells["epsDensity"].Value.ToString();//原料密度
                uiTextBox6.Text = uiDataGridView1.Rows[e.RowIndex].Cells["completNumber"].Value.ToString();//已生产数量
                uiTextBox4.Text = uiDataGridView1.Rows[e.RowIndex].Cells["totalNumber"].Value.ToString();//下达任务总数量

                var datalist = db.Queryable<OrderModel>().Select(it => new OrderModel
                {
                    remainder = it.remainder
                })
                .Where(it => it.id == Convert.ToInt32(uiComboDataGridView1.Text)).ToList();
                if (datalist.Count > 0)
                {
                    uiTextBox3.Text = datalist[0].remainder.ToString();//订单剩余数量
                }

                uiSymbolButton2.Enabled = true;
                uiSymbolButton5.Enabled = true;
                uiSymbolButton6.Enabled = true;
                UIMessageTip.ShowOk("调用 - 状态");
            }
        }

        private void uiSymbolButton1_Click(object sender, EventArgs e)
        {
            //新增按钮
            ProductionOrderModel dataList = new ProductionOrderModel()
            {
                orderCode = uiComboDataGridView1.Text,
                recipeCode = uiComboDataGridView2.Text,
                deviceCode = uiComboDataGridView3.Text,
                contractCode = uiTextBox10.Text,
                materialCode = uiTextBox12.Text,
                moldCode = uiTextBox2.Text,
                singleNumber = Convert.ToInt32(uiTextBox9.Text),
                epsDensity = uiTextBox1.Text,
                totalNumber = Convert.ToInt32(uiTextBox4.Text),
                completNumber = 0,
                state = "新增",
                //completDate = Convert.ToDateTime(uiDatePicker2.Text),
                creationDate = Convert.ToDateTime(uiDatePicker2.Text)
            };
            //******订单更新******
            try
            {
                db.BeginTran();
                //新增
                var x = db.Storageable(dataList)
                    .WhereColumns(it => new { it.id })
                    .ToStorage();
                x.AsInsertable.ExecuteCommand();//不存在插入

                if (x.InsertList.Count > 0)
                {

                    //订单更新
                    db.Updateable<OrderModel>()
                    .SetColumns(it => new OrderModel()
                    {
                        remainder = it.remainder - Convert.ToInt32(uiTextBox4.Text)
                    })
                    .Where(it => it.id == Convert.ToInt32(uiComboDataGridView1.Text)).ExecuteCommand();

                    var datalist = db.Queryable<OrderModel>().Select(it => new OrderModel
                    {
                        remainder = it.remainder
                    })
                    .Where(it => it.id == Convert.ToInt32(uiComboDataGridView1.Text)).ToList();
                    if (datalist.Count > 0)
                    {
                        uiTextBox3.Text = datalist[0].remainder.ToString();//订单剩余数量
                    }

                    UIMessageTip.ShowOk("新增生产订单 - 成功");
                }
                else
                {
                    UIMessageTip.ShowWarning("已有生产订单 - 警告");
                }

                db.CommitTran();
            }
            catch (Exception ex)
            {
                db.RollbackTran();//数据回滚
                UIMessageTip.ShowError("插入失败 - 数据回滚!\n" + ex);
            }

            if (!backgroundWorker1.IsBusy)
                backgroundWorker1.RunWorkerAsync();
        }

        private void uiSymbolButton5_Click(object sender, EventArgs e)
        {
            //更新按钮
            try
            {
                db.BeginTran();

                int count = db.Updateable<ProductionOrderModel>()
                .SetColumns(it => new ProductionOrderModel()
                {
                    orderCode = uiComboDataGridView1.Text,
                    recipeCode = uiComboDataGridView2.Text,
                    deviceCode = uiComboDataGridView3.Text,
                    moldCode = uiTextBox2.Text,
                    singleNumber = Convert.ToInt32(uiTextBox9.Text),
                    epsDensity = uiTextBox1.Text,
                    totalNumber = Convert.ToInt32(uiTextBox4.Text),
                    creationDate = Convert.ToDateTime(uiDatePicker2.Text),
                    contractCode = uiTextBox10.Text,
                    materialCode = uiTextBox12.Text
                })
                .Where(it => it.id == Convert.ToInt32(uiTextBox8.Text)).ExecuteCommand();

                db.CommitTran();

                if (count > 0)
                    UIMessageTip.ShowOk("更新生产订单 - 成功");
                else
                    UIMessageTip.ShowWarning("未查询到生产订单 - 警告");
            }
            catch (Exception ex)
            {
                db.RollbackTran();//数据回滚
                UIMessageTip.ShowError("插入失败 - 数据回滚!\n" + ex);
            }

            if (!backgroundWorker1.IsBusy)
                backgroundWorker1.RunWorkerAsync();
        }

        private void uiSymbolButton2_Click(object sender, EventArgs e)
        {
            //删除按钮
            try
            {
                db.BeginTran();

                int count = db.Deleteable<ProductionOrderModel>().Where(it => it.id == Convert.ToInt32(uiTextBox8.Text)).ExecuteCommand();

                if (count > 0)
                {
                    //订单更新
                    db.Updateable<OrderModel>()
                    .SetColumns(it => new OrderModel()
                    {
                        remainder = it.remainder + Convert.ToInt32(uiTextBox4.Text)
                    })
                    .Where(it => it.id == Convert.ToInt32(uiComboDataGridView1.Text)).ExecuteCommand();
                    
                    var datalist = db.Queryable<OrderModel>().Select(it => new OrderModel
                    {
                        remainder = it.remainder
                    })
                    .Where(it => it.id == Convert.ToInt32(uiComboDataGridView1.Text)).ToList();
                    if (datalist.Count > 0)
                    {
                        uiTextBox3.Text = datalist[0].remainder.ToString();//订单剩余数量
                    }

                    UIMessageTip.ShowOk("删除生产订单 - 成功");
                }
                else
                {
                    UIMessageTip.ShowWarning("未查询到生产订单 - 警告");
                }
                   
                db.CommitTran();

            }
            catch (Exception ex)
            {
                db.RollbackTran();//数据回滚
                UIMessageTip.ShowError("插入失败 - 数据回滚!\n" + ex);
            }

            if (!backgroundWorker1.IsBusy)
                backgroundWorker1.RunWorkerAsync();
        }

        private void uiSymbolButton6_Click(object sender, EventArgs e)
        {
            //下达生产任务按钮
            try
            {
                db.BeginTran();

                bool datafalg = db.Queryable<ProductionOrderModel>()
                    .Any(it => it.deviceCode == uiComboDataGridView3.Text && it.state == "准备");

                if (datafalg == true)
                {
                    UIMessageTip.ShowWarning("设备存在任务 - 警告");
                }
                else
                {
                    int count = db.Updateable<ProductionOrderModel>()
                        .SetColumns(it => new ProductionOrderModel()
                        {
                            state = "准备"
                        })
                        .Where(it => it.id == Convert.ToInt32(uiTextBox8.Text)).ExecuteCommand();

                    if (count > 0)
                        UIMessageTip.ShowOk("下达任务 - 成功");
                    else
                        UIMessageTip.ShowWarning("未查询到生产任务 - 警告");
                }

                db.CommitTran();
                
            }
            catch (Exception ex)
            {
                db.RollbackTran();//数据回滚
                UIMessageTip.ShowError("下达失败 - 数据回滚!" + ex);
            }

            if (!backgroundWorker1.IsBusy)
                backgroundWorker1.RunWorkerAsync();
        }

        private void uiSymbolButton3_Click(object sender, EventArgs e)
        {
            //搜索按钮
            try
            {
                db.BeginTran();

                uiDataGridView1.DataSource = db.Queryable<ProductionOrderModel>().
                    Where(it => it.state == "新增" && it.orderCode.Contains(uiTextBox5.Text) && it.recipeCode.Contains(uiTextBox11.Text) && it.deviceCode.Contains(uiTextBox7.Text)).
                    OrderBy(it => it.id, OrderByType.Desc).ToList();

                db.CommitTran();
            }
            catch (Exception ex)
            {
                db.RollbackTran();//数据回滚
                UIMessageTip.ShowError("插入失败 - 数据回滚!\n" + ex);
            }

            uiSymbolButton2.Enabled = false;
            uiSymbolButton5.Enabled = false;
            uiSymbolButton6.Enabled = false;
        }

        private void uiSymbolButton4_Click(object sender, EventArgs e)
        {
            //清除按钮
            uiTextBox5.Clear();//工艺编号
            uiTextBox11.Clear();//原料密度
            uiTextBox7.Clear();//模具编号

            if (!backgroundWorker1.IsBusy)
                backgroundWorker1.RunWorkerAsync();
        }

        private void uiComboDataGridView1_ValueChanged(object sender, object value)
        {
            //订单
            if (value != null)
            {
                uiComboDataGridView1.Text = order_dt.Rows[((DataGridViewRow)value).Index]["id"].ToString();//订单编号
                uiTextBox10.Text = order_dt.Rows[((DataGridViewRow)value).Index]["contractCode"].ToString();//合同号
                uiTextBox12.Text = order_dt.Rows[((DataGridViewRow)value).Index]["materialCode"].ToString();//物料编码
                uiTextBox3.Text = order_dt.Rows[((DataGridViewRow)value).Index]["remainder"].ToString();//订单剩余数量
            }
        }

        private void uiComboDataGridView2_ValueChanged(object sender, object value)
        {
            //工艺
            if (value != null)
            {
                uiComboDataGridView2.Text = recipe_dt.Rows[((DataGridViewRow)value).Index]["processCode"].ToString();//工艺编号
                uiTextBox2.Text = recipe_dt.Rows[((DataGridViewRow)value).Index]["mouldCode"].ToString();//模具编号
                uiTextBox1.Text = recipe_dt.Rows[((DataGridViewRow)value).Index]["epsDensity"].ToString();//原料密度
                uiTextBox9.Text = recipe_dt.Rows[((DataGridViewRow)value).Index]["singleNumber"].ToString();//模具产品数
            }
        }

        private void uiComboDataGridView3_ValueChanged(object sender, object value)
        {
            //设备
            if (value != null)
            {
                uiComboDataGridView3.Text = device_dt.Rows[((DataGridViewRow)value).Index]["deviceCode"].ToString();//设备编号
            }
        }
    }
}
